package com.fowo.api.syncAmazon.service.impl;

import com.amazon.spapi.client.ApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.FbaShipment;
import com.fowo.api.entity.ListingFather;
import com.fowo.api.entity.TmpFbaShipment;
import com.fowo.api.entity.TmpFbaShipmentProduct;
import com.fowo.api.model.fba.shipment.FbaShipmentVo;
import com.fowo.api.model.fba.shipment.product.FbaShipmentProductItemVo;
import com.fowo.api.service.impl.FbaShipmentBaseServiceImpl;
import com.fowo.api.service.impl.ListingFatherServiceImpl;
import com.fowo.api.service.impl.TmpFbaShipmentProductServiceImpl;
import com.fowo.api.service.impl.TmpFbaShipmentServiceImpl;
import com.fowo.api.syncAmazon.api.ShipmentService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SyncShipmentServiceImpl {
    @Resource
    private ShipmentService shipmentService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;
    @Resource
    private TmpFbaShipmentServiceImpl tmpFbaShipmentService;
    @Resource
    private TmpFbaShipmentProductServiceImpl tmpFbaShipmentProductService;
    @Resource
    private FbaShipmentBaseServiceImpl fbaShipmentService;
    @Resource
    private ListingFatherServiceImpl listingFatherService;

    public void syncShipment() throws ApiException {
        //清空临时表
        amazonTmpMapper.deleteTmpFbaShipment();
        amazonTmpMapper.deleteTmpFbaShipmentProduct();

        //保存到临时表
        List<TmpFbaShipment> tmpFbaShipments = shipmentService.getShipments();
        tmpFbaShipmentService.saveBatch(tmpFbaShipments);
        List<TmpFbaShipmentProduct> tmpFbaShipmentProducts = shipmentService.getShipmentItems();
        tmpFbaShipmentProductService.saveBatch(tmpFbaShipmentProducts);

        //保存到业务表
        saveToFbaShipment(tmpFbaShipments,tmpFbaShipmentProducts);

    }

    /**
     * 保存到业务表
     * @param tmpFbaShipments
     * @param tmpFbaShipmentProducts
     */
    public void saveToFbaShipment(List<TmpFbaShipment> tmpFbaShipments,List<TmpFbaShipmentProduct> tmpFbaShipmentProducts){
        for(TmpFbaShipment tmpFbaShipment : tmpFbaShipments){
            FbaShipment fbaShipment = fbaShipmentService.getOne(Wrappers.lambdaQuery(FbaShipment.class)
                    .eq(FbaShipment::getShipmentId, tmpFbaShipment.getShipmentId()));
            if(null == fbaShipment){
                FbaShipmentVo model = new FbaShipmentVo();
                model.setShipmentId(tmpFbaShipment.getShipmentId());
                fbaShipment.setShop(tmpFbaShipment.getSid());
                fbaShipment.setCountry(tmpFbaShipment.getCountry());
                model.setDestinationFulfillmentCenterId(tmpFbaShipment.getDestinationFulfillmentCenterId());
                model.setShipmentStatus(tmpFbaShipment.getShipmentStatus());
                model.setLabelType(tmpFbaShipment.getLabelPrepType());
                model.setShipmentName(tmpFbaShipment.getShipmentName());
                model.setPackingType(tmpFbaShipment.getAreCasesRequired()?"2":"1");
                model.setConsignerName(tmpFbaShipment.getName());
                model.setShipmentsCountry(tmpFbaShipment.getCountryCode());
                model.setStreetAddress(tmpFbaShipment.getAddressLine());
                model.setCity(tmpFbaShipment.getCity());
                model.setCounty(tmpFbaShipment.getDistrictOrCounty());
                model.setProvince(tmpFbaShipment.getStateOrProvinceCode());
                model.setPostcode(tmpFbaShipment.getPostalCode());
                model.setIsSynchronous("1");
                List<FbaShipmentProductItemVo> list = new ArrayList<>();
                List<TmpFbaShipmentProduct> productList = tmpFbaShipmentProducts.stream().filter(p -> p.getShipmentId().equals(tmpFbaShipment.getShipmentId())).collect(Collectors.toList());
                tmpFbaShipmentProducts.removeAll(productList);
                for(TmpFbaShipmentProduct product : productList){
                    FbaShipmentProductItemVo item = new FbaShipmentProductItemVo();
                    ListingFather listingFather = listingFatherService.getOne(Wrappers.lambdaQuery(ListingFather.class)
                            .eq(ListingFather::getShop, "")
                            .eq(ListingFather::getMsku, product.getSellerSku())
                            .eq(ListingFather::getFnsku, product.getFulfillmentNetworkSku()));
                    item.setImg(listingFather.getImg());
                    item.setMsku(product.getSellerSku());
                    item.setFnsku(product.getFulfillmentNetworkSku());
                    item.setAsin(listingFather.getAsin());
                    item.setParentAsin(listingFather.getParentAsin());
                    item.setProductName(listingFather.getPairProduct());
                    item.setSku(listingFather.getSku());
                    item.setAmountDeclared(product.getQuantityShipped());
                    if(tmpFbaShipment.getShipmentStatus().equals("WORKING")){
                        item.setQuantityShippedLocal(0);
                        item.setShenFaDifference(product.getQuantityShipped());
                    }else{
                        item.setQuantityShippedLocal(product.getQuantityShipped());
                        item.setShenFaDifference(0);
                    }
                    Integer quantityReceived = product.getQuantityReceived() == null ? 0 : product.getQuantityReceived();
                    item.setQuantityReceived(quantityReceived);
                    item.setShouFaDifference(quantityReceived-item.getQuantityShippedLocal());
                    item.setShenShouDifference(product.getQuantityShipped()-quantityReceived);
                    item.setQuantityPerCarton(product.getQuantityInCase() == null ? 0 : product.getQuantityInCase());
                    item.setIsSynchronous("1");

                    list.add(item);
                }
                model.setList(list);
                try{
                    fbaShipmentService.create(model);
                }catch (Exception e){
                    log.error("添加货件："+tmpFbaShipment.getShipmentId()+" 异常",e);
                }
            }else {
                fbaShipment.setShipmentStatus(tmpFbaShipment.getShipmentStatus());
                fbaShipmentService.updateById(fbaShipment);
            }
        }
    }

    /**
     * 手动同步FBA货件
     * @param shopId
     * @param shipmentIdList
     */
    public void manualSyncShipment(Long shopId, List<String> shipmentIdList) throws ApiException {
        //清空临时表
        amazonTmpMapper.deleteTmpFbaShipment();
        amazonTmpMapper.deleteTmpFbaShipmentProduct();

        //保存到临时表
        List<TmpFbaShipment> tmpFbaShipments = shipmentService.getShipments(shopId, shipmentIdList);
        tmpFbaShipmentService.saveBatch(tmpFbaShipments);
        List<TmpFbaShipmentProduct> tmpFbaShipmentProducts = shipmentService.getShipmentItems(shopId, shipmentIdList);
        tmpFbaShipmentProductService.saveBatch(tmpFbaShipmentProducts);

        //保存到业务表
        saveToFbaShipment(tmpFbaShipments,tmpFbaShipmentProducts);
    }
}
